//! Command processing for Redis-rs2
//! 
//! This module provides command definitions and processing logic that will be used
//! by the network layer to handle Redis commands. It acts as a bridge between
//! the network protocol layer and the storage layer.

use crate::error::{Result, StorageError};
// use crate::storage::Storage;  // Legacy Storage已删除
use serde::{Serialize, Deserialize};

// Temporary stub for Storage (removed legacy module)
// TODO: Refactor Command trait to use SingleThreadStorage or remove this dependency
#[derive(Debug)]
pub struct Storage;

impl Storage {
    pub fn new() -> Self {
        Self
    }
    
    pub fn get(&self, _key: &str) -> Result<Option<String>> {
        Ok(None)
    }
    
    pub fn set(&self, _key: &str, _value: &str) -> Result<()> {
        Ok(())
    }
    
    pub fn del(&self, _key: &str) -> bool {
        false
    }
    
    pub fn exists(&self, _key: &str) -> bool {
        false
    }
    
    pub fn incr(&self, _key: &str) -> Result<i64> {
        Ok(1)
    }
    
    pub fn incr_by(&self, _key: &str, _increment: i64) -> Result<i64> {
        Ok(_increment)
    }
    
    pub fn hset(&self, _key: &str, _field: &str, _value: &str) -> Result<bool> {
        Ok(true)
    }
    
    pub fn hget(&self, _key: &str, _field: &str) -> Result<Option<String>> {
        Ok(None)
    }
    
    pub fn hdel(&self, _key: &str, _fields: &[String]) -> Result<i64> {
        Ok(0)
    }
    
    pub fn clear(&self) {
        // No-op
    }
    
    pub fn get_type(&self, _key: &str) -> Option<String> {
        None
    }
    
    pub fn expire(&self, _key: &str, _seconds: u64) -> Result<bool> {
        Ok(false)
    }
    
    pub fn ttl(&self, _key: &str) -> i64 {
        -2  // Key doesn't exist
    }
    
    pub fn persist(&self, _key: &str) -> Result<bool> {
        Ok(false)
    }
}

impl Default for Storage {
    fn default() -> Self {
        Self::new()
    }
}

/// Base trait for all Redis commands
/// 
/// Each command type implements this trait to provide type-safe command handling
/// with compile-time parameter validation.
pub trait Command: Send + Sync + std::fmt::Debug {
    /// Get the command name (e.g., "GET", "SET", "HSET")
    fn name(&self) -> &'static str;
    
    /// Execute the command against the storage
    fn execute(&self, storage: &Storage) -> Result<CommandResult>;
    
    /// Convert the command to RESP format arguments for serialization
    fn to_args(&self) -> Vec<String>;
    
    /// Get a debug representation of the command
    fn debug_string(&self) -> String {
        format!("{}({})", self.name(), self.to_args().join(", "))
    }
}

/// Factory for creating commands from raw arguments
pub struct CommandFactory;

impl CommandFactory {
    /// Create a command from name and arguments
    pub fn create(name: String, args: Vec<String>) -> Result<Box<dyn Command>> {
        let cmd_name = name.to_uppercase();
        
        match cmd_name.as_str() {
            "GET" => Ok(Box::new(GetCommand::new(args)?)),
            "SET" => Ok(Box::new(SetCommand::new(args)?)),
            "DEL" => Ok(Box::new(DelCommand::new(args)?)),
            "EXISTS" => Ok(Box::new(ExistsCommand::new(args)?)),
            "INCR" => Ok(Box::new(IncrCommand::new(args)?)),
            "INCRBY" => Ok(Box::new(IncrByCommand::new(args)?)),
            "DECR" => Ok(Box::new(DecrCommand::new(args)?)),
            "DECRBY" => Ok(Box::new(DecrByCommand::new(args)?)),
            "HSET" => Ok(Box::new(HSetCommand::new(args)?)),
            "HGET" => Ok(Box::new(HGetCommand::new(args)?)),
            "HDEL" => Ok(Box::new(HDelCommand::new(args)?)),
            "EXPIRE" => Ok(Box::new(ExpireCommand::new(args)?)),
            "TTL" => Ok(Box::new(TtlCommand::new(args)?)),
            "PERSIST" => Ok(Box::new(PersistCommand::new(args)?)),
            "PING" => Ok(Box::new(PingCommand::new(args)?)),
            "FLUSHALL" => Ok(Box::new(FlushAllCommand::new(args)?)),
            "TYPE" => Ok(Box::new(TypeCommand::new(args)?)),
            "CLIENT" => Ok(Box::new(ClientCommand::new(args)?)),
            "CLUSTER" => Ok(Box::new(ClusterCommand::new(args)?)),
            "PROTOCOL_ERROR_RESPONSE" => {
                if args.len() != 2 {
                    return Err(StorageError::InvalidArgument {
                        message: format!("wrong number of arguments for 'PROTOCOL_ERROR_RESPONSE' command: expected 2, got {}", args.len())
                    });
                }
                let connection_id = args[1].parse::<u64>().map_err(|_| StorageError::InvalidArgument {
                    message: "Invalid connection ID".to_string()
                })?;
                Ok(Box::new(ProtocolErrorResponseCommand::new(args[0].clone(), connection_id)))
            },
            _ => Err(StorageError::OperationNotSupported {
                operation: name,
            }),
        }
    }
}

/// Result of command execution
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CommandResult {
    /// OK response
    Ok,
    /// String response
    String(String),
    /// Integer response
    Integer(i64),
    /// Boolean response (0 or 1)
    Boolean(bool),
    /// Array response
    Array(Vec<CommandResult>),
    /// Null response
    Null,
    /// Error response
    Error(String),
}

impl CommandResult {
    /// Convert CommandResult to RESP format string (simplified)
    pub fn to_resp(&self) -> String {
        match self {
            CommandResult::Ok => "+OK\r\n".to_string(),
            CommandResult::String(s) => format!("${}\r\n{}\r\n", s.len(), s),
            CommandResult::Integer(i) => format!(":{i}\r\n"),
            CommandResult::Boolean(b) => format!(":{}\r\n", if *b { 1 } else { 0 }),
            CommandResult::Array(arr) => {
                let mut resp = format!("*{}\r\n", arr.len());
                for item in arr {
                    resp.push_str(&item.to_resp());
                }
                resp
            }
            CommandResult::Null => "$-1\r\n".to_string(),
            CommandResult::Error(msg) => format!("-{msg}\r\n"),
        }
    }
}

/// Command processor that handles execution of Redis commands
pub struct CommandProcessor {
    storage: Storage,
}

impl CommandProcessor {
    /// Create a new command processor
    pub fn new(storage: Storage) -> Self {
        Self { storage }
    }
    
    /// Execute a command and return the result
    pub fn execute(&self, command: Box<dyn Command>) -> CommandResult {
        match command.execute(&self.storage) {
            Ok(result) => result,
            Err(e) => CommandResult::Error(e.to_string()),
        }
    }
}

// === String Commands ===

/// GET command - get a string value
#[derive(Debug, Clone)]
pub struct GetCommand {
    key: String,
}

impl GetCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 1 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'GET' command: expected 1, got {}", args.len())
            });
        }
        Ok(Self {
            key: args[0].clone(),
        })
    }
    
    pub fn key(&self) -> &str {
        &self.key
    }
}

impl Command for GetCommand {
    fn name(&self) -> &'static str {
        "GET"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        match storage.get(&self.key)? {
            Some(value) => Ok(CommandResult::String(value)),
            None => Ok(CommandResult::Null),
        }
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone()]
    }
}

/// SET command - set a string value
#[derive(Debug, Clone)]
pub struct SetCommand {
    key: String,
    value: String,
}

impl SetCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 2 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'SET' command: expected 2, got {}", args.len())
            });
        }
        Ok(Self {
            key: args[0].clone(),
            value: args[1].clone(),
        })
    }
    
    pub fn key(&self) -> &str {
        &self.key
    }
    
    pub fn value(&self) -> &str {
        &self.value
    }
}

impl Command for SetCommand {
    fn name(&self) -> &'static str {
        "SET"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        storage.set(&self.key, &self.value)?;
        Ok(CommandResult::Ok)
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone(), self.value.clone()]
    }
}

/// Protocol Error Response command - special command for protocol parsing errors
/// 
/// This is a special command that is not a real Redis command, but is used to
/// handle protocol parsing errors. When the protocol layer encounters a parsing
/// error, it creates this command and sends it to the storage layer. The storage
/// layer doesn't actually execute this command, but instead sends an error
/// response back through the response queue, allowing the response thread to
/// write the error response to the client and then close the connection.
#[derive(Debug, Clone)]
pub struct ProtocolErrorResponseCommand {
    /// Error message to send to the client
    error_message: String,
    /// Connection ID for routing the response
    connection_id: u64,
}

impl ProtocolErrorResponseCommand {
    pub fn new(error_message: String, connection_id: u64) -> Self {
        Self {
            error_message,
            connection_id,
        }
    }
    
    pub fn error_message(&self) -> &str {
        &self.error_message
    }
    
    pub fn connection_id(&self) -> u64 {
        self.connection_id
    }
}

impl Command for ProtocolErrorResponseCommand {
    fn name(&self) -> &'static str {
        "PROTOCOL_ERROR_RESPONSE"
    }
    
    fn execute(&self, _storage: &Storage) -> Result<CommandResult> {
        // This command is special - it's not actually executed by the storage layer.
        // Instead, it's sent to the response queue to be handled by the response thread.
        // The storage layer just returns the error message as a CommandResult::Error,
        // which will be sent back through the response queue.
        Ok(CommandResult::Error(self.error_message.clone()))
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.error_message.clone(), self.connection_id.to_string()]
    }
}

/// DEL command - delete one or more keys
#[derive(Debug, Clone)]
pub struct DelCommand {
    keys: Vec<String>,
}

impl DelCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.is_empty() {
            return Err(StorageError::InvalidArgument {
                message: "wrong number of arguments for 'DEL' command: at least 1 required".to_string()
            });
        }
        Ok(Self {
            keys: args,
        })
    }
    
    pub fn keys(&self) -> &[String] {
        &self.keys
    }
}

impl Command for DelCommand {
    fn name(&self) -> &'static str {
        "DEL"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        let mut deleted = 0;
        for key in &self.keys {
            if storage.del(key) {
                deleted += 1;
            }
        }
        Ok(CommandResult::Integer(deleted))
    }
    
    fn to_args(&self) -> Vec<String> {
        self.keys.clone()
    }
}

/// EXISTS command - check if one or more keys exist
#[derive(Debug, Clone)]
pub struct ExistsCommand {
    keys: Vec<String>,
}

impl ExistsCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.is_empty() {
            return Err(StorageError::InvalidArgument {
                message: "wrong number of arguments for 'EXISTS' command: at least 1 required".to_string()
            });
        }
        Ok(Self {
            keys: args,
        })
    }
    
    pub fn keys(&self) -> &[String] {
        &self.keys
    }
}

impl Command for ExistsCommand {
    fn name(&self) -> &'static str {
        "EXISTS"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        let mut count = 0;
        for key in &self.keys {
            if storage.exists(key) {
                count += 1;
            }
        }
        Ok(CommandResult::Integer(count))
    }
    
    fn to_args(&self) -> Vec<String> {
        self.keys.clone()
    }
}

/// INCR command - increment a key's integer value
#[derive(Debug, Clone)]
pub struct IncrCommand {
    key: String,
}

impl IncrCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 1 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'INCR' command: expected 1, got {}", args.len())
            });
        }
        Ok(Self {
            key: args[0].clone(),
        })
    }
    
    pub fn key(&self) -> &str {
        &self.key
    }
}

impl Command for IncrCommand {
    fn name(&self) -> &'static str {
        "INCR"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        let result = storage.incr(&self.key)?;
        Ok(CommandResult::Integer(result))
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone()]
    }
}

/// INCRBY command - increment a key's integer value by amount
#[derive(Debug, Clone)]
pub struct IncrByCommand {
    key: String,
    amount: i64,
}

impl IncrByCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 2 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'INCRBY' command: expected 2, got {}", args.len())
            });
        }
        
        let amount = args[1].parse::<i64>()
            .map_err(|_| StorageError::InvalidArgument {
                message: "value is not an integer or out of range".to_string()
            })?;
            
        Ok(Self {
            key: args[0].clone(),
            amount,
        })
    }
    
    pub fn key(&self) -> &str {
        &self.key
    }
    
    pub fn amount(&self) -> i64 {
        self.amount
    }
}

impl Command for IncrByCommand {
    fn name(&self) -> &'static str {
        "INCRBY"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        let result = storage.incr_by(&self.key, self.amount)?;
        Ok(CommandResult::Integer(result))
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone(), self.amount.to_string()]
    }
}

/// DECR command - decrement a key's integer value
#[derive(Debug, Clone)]
pub struct DecrCommand {
    key: String,
}

impl DecrCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 1 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'DECR' command: expected 1, got {}", args.len())
            });
        }
        Ok(Self {
            key: args[0].clone(),
        })
    }
    
    pub fn key(&self) -> &str {
        &self.key
    }
}

impl Command for DecrCommand {
    fn name(&self) -> &'static str {
        "DECR"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        let result = storage.incr_by(&self.key, -1)?;
        Ok(CommandResult::Integer(result))
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone()]
    }
}

/// DECRBY command - decrement a key's integer value by amount
#[derive(Debug, Clone)]
pub struct DecrByCommand {
    key: String,
    amount: i64,
}

impl DecrByCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 2 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'DECRBY' command: expected 2, got {}", args.len())
            });
        }
        
        let amount = args[1].parse::<i64>()
            .map_err(|_| StorageError::InvalidArgument {
                message: "value is not an integer or out of range".to_string()
            })?;
            
        Ok(Self {
            key: args[0].clone(),
            amount,
        })
    }
    
    pub fn key(&self) -> &str {
        &self.key
    }
    
    pub fn amount(&self) -> i64 {
        self.amount
    }
}

impl Command for DecrByCommand {
    fn name(&self) -> &'static str {
        "DECRBY"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        let result = storage.incr_by(&self.key, -self.amount)?;
        Ok(CommandResult::Integer(result))
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone(), self.amount.to_string()]
    }
}

// === Hash Commands ===

/// HSET command - set hash field
#[derive(Debug, Clone)]
pub struct HSetCommand {
    key: String,
    field: String,
    value: String,
}

impl HSetCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 3 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'HSET' command: expected 3, got {}", args.len())
            });
        }
        Ok(Self {
            key: args[0].clone(),
            field: args[1].clone(),
            value: args[2].clone(),
        })
    }
}

impl Command for HSetCommand {
    fn name(&self) -> &'static str {
        "HSET"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        let is_new = storage.hset(&self.key, &self.field, &self.value)?;
        Ok(CommandResult::Integer(if is_new { 1 } else { 0 }))
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone(), self.field.clone(), self.value.clone()]
    }
}

/// HGET command - get hash field value
#[derive(Debug, Clone)]
pub struct HGetCommand {
    key: String,
    field: String,
}

impl HGetCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 2 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'HGET' command: expected 2, got {}", args.len())
            });
        }
        Ok(Self {
            key: args[0].clone(),
            field: args[1].clone(),
        })
    }
}

impl Command for HGetCommand {
    fn name(&self) -> &'static str {
        "HGET"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        match storage.hget(&self.key, &self.field)? {
            Some(value) => Ok(CommandResult::String(value)),
            None => Ok(CommandResult::Null),
        }
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone(), self.field.clone()]
    }
}

/// HDEL command - delete hash field
#[derive(Debug, Clone)]
pub struct HDelCommand {
    key: String,
    field: String,
}

impl HDelCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 2 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'HDEL' command: expected 2, got {}", args.len())
            });
        }
        Ok(Self {
            key: args[0].clone(),
            field: args[1].clone(),
        })
    }
}

impl Command for HDelCommand {
    fn name(&self) -> &'static str {
        "HDEL"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        let deleted = storage.hdel(&self.key, &[self.field.clone()])?;
        Ok(CommandResult::Integer(deleted))
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone(), self.field.clone()]
    }
}

// === Server Commands ===

/// PING command - ping server
#[derive(Debug, Clone)]
pub struct PingCommand;

impl PingCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if !args.is_empty() {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'PING' command: expected 0, got {}", args.len())
            });
        }
        Ok(Self)
    }
}

impl Command for PingCommand {
    fn name(&self) -> &'static str {
        "PING"
    }
    
    fn execute(&self, _storage: &Storage) -> Result<CommandResult> {
        Ok(CommandResult::String("PONG".to_string()))
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![]
    }
}

/// FLUSHALL command - clear all data
#[derive(Debug, Clone)]
pub struct FlushAllCommand;

impl FlushAllCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if !args.is_empty() {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'FLUSHALL' command: expected 0, got {}", args.len())
            });
        }
        Ok(Self)
    }
}

impl Command for FlushAllCommand {
    fn name(&self) -> &'static str {
        "FLUSHALL"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        storage.clear();
        Ok(CommandResult::Ok)
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![]
    }
}

/// TYPE command - get key type
#[derive(Debug, Clone)]
pub struct TypeCommand {
    key: String,
}

impl TypeCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 1 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'TYPE' command: expected 1, got {}", args.len())
            });
        }
        Ok(Self {
            key: args[0].clone(),
        })
    }
}

impl Command for TypeCommand {
    fn name(&self) -> &'static str {
        "TYPE"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        match storage.get_type(&self.key) {
            Some(type_name) => Ok(CommandResult::String(type_name)),
            None => Ok(CommandResult::String("none".to_string())),
        }
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone()]
    }
}

/// TTL Operations
#[derive(Debug, Clone)]
pub struct ExpireCommand {
    key: String,
    seconds: u64,
}

impl ExpireCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 2 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'EXPIRE' command: expected 2, got {}", args.len())
            });
        }
        
        let seconds = args[1].parse::<u64>()
            .map_err(|_| StorageError::InvalidArgument {
                message: "timeout is not an integer or out of range".to_string()
            })?;
            
        Ok(Self {
            key: args[0].clone(),
            seconds,
        })
    }
}

impl Command for ExpireCommand {
    fn name(&self) -> &'static str {
        "EXPIRE"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        let result = storage.expire(&self.key, self.seconds)?;
        Ok(CommandResult::Integer(if result { 1 } else { 0 }))
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone(), self.seconds.to_string()]
    }
}

#[derive(Debug, Clone)]
pub struct TtlCommand {
    key: String,
}

impl TtlCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 1 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'TTL' command: expected 1, got {}", args.len())
            });
        }
        Ok(Self {
            key: args[0].clone(),
        })
    }
}

impl Command for TtlCommand {
    fn name(&self) -> &'static str {
        "TTL"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        let ttl = storage.ttl(&self.key);
        Ok(CommandResult::Integer(ttl))
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone()]
    }
}

#[derive(Debug, Clone)]
pub struct PersistCommand {
    key: String,
}

impl PersistCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.len() != 1 {
            return Err(StorageError::InvalidArgument {
                message: format!("wrong number of arguments for 'PERSIST' command: expected 1, got {}", args.len())
            });
        }
        Ok(Self {
            key: args[0].clone(),
        })
    }
}

impl Command for PersistCommand {
    fn name(&self) -> &'static str {
        "PERSIST"
    }
    
    fn execute(&self, storage: &Storage) -> Result<CommandResult> {
        let result = storage.persist(&self.key)?;
        Ok(CommandResult::Integer(if result { 1 } else { 0 }))
    }
    
    fn to_args(&self) -> Vec<String> {
        vec![self.key.clone()]
    }
}

/// CLIENT command - client-specific operations
#[derive(Debug, Clone)]
pub struct ClientCommand {
    subcommand: String,
    args: Vec<String>,
}

impl ClientCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.is_empty() {
            return Err(StorageError::InvalidArgument {
                message: "wrong number of arguments for 'CLIENT' command: expected at least 1".to_string()
            });
        }
        
        let subcommand = args[0].clone().to_uppercase();
        let remaining_args = if args.len() > 1 {
            args[1..].to_vec()
        } else {
            Vec::new()
        };
        
        Ok(Self {
            subcommand,
            args: remaining_args,
        })
    }
}

impl Command for ClientCommand {
    fn name(&self) -> &'static str {
        "CLIENT"
    }
    
    fn execute(&self, _storage: &Storage) -> Result<CommandResult> {
        match self.subcommand.as_str() {
            "SETINFO" => {
                // CLIENT SETINFO is used by Redis clients to identify themselves
                // We simply acknowledge it with OK
                Ok(CommandResult::Ok)
            }
            "GETNAME" => {
                // Return client name (we don't track names, so return null)
                Ok(CommandResult::Null)
            }
            "ID" => {
                // Return a mock client ID
                Ok(CommandResult::Integer(1))
            }
            "LIST" => {
                // Return empty client list for now
                Ok(CommandResult::String("".to_string()))
            }
            _ => {
                Ok(CommandResult::Error(format!("Unknown CLIENT subcommand: {}", self.subcommand)))
            }
        }
    }
    
    fn to_args(&self) -> Vec<String> {
        let mut result = vec![self.subcommand.clone()];
        result.extend(self.args.clone());
        result
    }
}

/// CLUSTER command - handle cluster operations
#[derive(Debug, Clone)]
pub struct ClusterCommand {
    subcommand: String,
    args: Vec<String>,
}

impl ClusterCommand {
    pub fn new(args: Vec<String>) -> Result<Self> {
        if args.is_empty() {
            return Err(StorageError::InvalidArgument {
                message: "CLUSTER command requires subcommand".to_string(),
            });
        }
        
        let subcommand = args[0].clone().to_uppercase();
        let remaining_args = args[1..].to_vec();
        
        Ok(Self {
            subcommand,
            args: remaining_args,
        })
    }
    
    pub fn subcommand(&self) -> &str {
        &self.subcommand
    }
    
    pub fn cluster_args(&self) -> &[String] {
        &self.args
    }
}

impl Command for ClusterCommand {
    fn name(&self) -> &'static str {
        "CLUSTER"
    }
    
    fn execute(&self, _storage: &Storage) -> Result<CommandResult> {
        // CLUSTER命令不在这里执行，而是在SingleThreadRedisServer中处理
        // 这里返回一个特殊错误表示需要路由到集群处理逻辑
        Err(StorageError::OperationNotSupported {
            operation: "CLUSTER commands should be routed to cluster handler".to_string(),
        })
    }
    
    fn to_args(&self) -> Vec<String> {
        let mut result = vec![self.subcommand.clone()];
        result.extend(self.args.clone());
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    fn setup_processor() -> CommandProcessor {
        let storage = Storage::new();
        CommandProcessor::new(storage)
    }
    
    #[test]
    fn test_command_factory() {
        // Test GET command
        let get_cmd = CommandFactory::create("GET".to_string(), vec!["key1".to_string()]).unwrap();
        assert_eq!(get_cmd.name(), "GET");
        assert_eq!(get_cmd.to_args(), vec!["key1".to_string()]);
        
        // Test SET command
        let set_cmd = CommandFactory::create("SET".to_string(), vec!["key1".to_string(), "value1".to_string()]).unwrap();
        assert_eq!(set_cmd.name(), "SET");
        assert_eq!(set_cmd.to_args(), vec!["key1".to_string(), "value1".to_string()]);
        
        // Test invalid command
        let invalid_cmd = CommandFactory::create("INVALID".to_string(), vec![]);
        assert!(invalid_cmd.is_err());
    }
    
    #[test]
    fn test_string_commands() {
        let processor = setup_processor();
        
        // Test SET
        let set_cmd = CommandFactory::create("SET".to_string(), vec!["key1".to_string(), "value1".to_string()]).unwrap();
        let result = processor.execute(set_cmd);
        assert_eq!(result, CommandResult::Ok);
        
        // Test GET
        let get_cmd = CommandFactory::create("GET".to_string(), vec!["key1".to_string()]).unwrap();
        let result = processor.execute(get_cmd);
        assert_eq!(result, CommandResult::String("value1".to_string()));
        
        // Test DEL
        let del_cmd = CommandFactory::create("DEL".to_string(), vec!["key1".to_string()]).unwrap();
        let result = processor.execute(del_cmd);
        assert_eq!(result, CommandResult::Integer(1));
    }
    
    #[test]
    fn test_server_commands() {
        let processor = setup_processor();
        
        // Test PING
        let ping_cmd = CommandFactory::create("PING".to_string(), vec![]).unwrap();
        let result = processor.execute(ping_cmd);
        assert_eq!(result, CommandResult::String("PONG".to_string()));
    }
    
    #[test]
    fn test_command_result_to_resp() {
        assert_eq!(CommandResult::Ok.to_resp(), "+OK\r\n");
        assert_eq!(CommandResult::String("hello".to_string()).to_resp(), "$5\r\nhello\r\n");
        assert_eq!(CommandResult::Integer(42).to_resp(), ":42\r\n");
        assert_eq!(CommandResult::Null.to_resp(), "$-1\r\n");
    }
    
    #[test]
    fn test_command_validation() {
        // Test invalid argument count for GET
        let get_cmd = CommandFactory::create("GET".to_string(), vec![]);
        assert!(get_cmd.is_err());
        
        // Test invalid argument count for SET
        let set_cmd = CommandFactory::create("SET".to_string(), vec!["key1".to_string()]);
        assert!(set_cmd.is_err());
        
        // Test invalid integer for INCRBY
        let incrby_cmd = CommandFactory::create("INCRBY".to_string(), vec!["key1".to_string(), "not_a_number".to_string()]);
        assert!(incrby_cmd.is_err());
    }
}